package org.example.im.server.handler.impl.biz;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import org.example.im.bean.protocol.CommandType;
import org.example.im.bean.protocol.request.Send2GroupRequestPacket;
import org.example.im.bean.protocol.response.Send2GroupResponsePacket;
import org.example.im.bean.session.Session;
import org.example.im.common.util.SessionUtil;
import org.example.im.server.handler.ServerHandler;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author dingrui
 * @since 2022/2/12
 * @description 群发消息
 */
@Component
public class Send2GroupHandler extends SimpleChannelInboundHandler<Send2GroupRequestPacket> implements ServerHandler {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Send2GroupRequestPacket request) throws Exception {
        // 群
        String groupId = request.getToGroupId();
        if (Objects.isNull(groupId)) return;
        Session fromUser = SessionUtil.getSession(ctx.channel());
        String msg = request.getMsg();
        Send2GroupResponsePacket response = Send2GroupResponsePacket.builder().fromGroupId(groupId).fromUser(fromUser).msg(msg).build();
        // channelGroup 发送每个客户端
        ChannelGroup channelGroup = SessionUtil.getChannelGroupByGroupId(groupId);
        channelGroup.writeAndFlush(response);
    }

    @Override
    public CommandType genType() {
        return CommandType.SEND_2_GROUP_REQUEST;
    }
}
